package com.s63.appinfo.controller;

import com.s63.appinfo.pojo.AjaxResult;
import com.s63.appinfo.pojo.LoginUser;
import com.s63.appinfo.service.BackendUserService;
import com.s63.appinfo.service.DevUserService;
import com.s63.appinfo.util.SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
public class LoginController {
    @Autowired
    private DevUserService devUserService;
    @Autowired
    private BackendUserService backendUserService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginUser loginUser) {
        try {
            loginUser.setId(getId(loginUser));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("用户名或密码错误");
        }
        // 生成uuid传递到前端，前端后续请求都需要在请求头中传递uuid到后端，以便识别登录用户
        String uuid = UUID.randomUUID().toString();
        // 保存uuid到后端
        SessionManager.getInstance().put(uuid, loginUser);
        return AjaxResult.ok(uuid);
    }

    public Long getId(LoginUser loginUser) {
        if (loginUser.getType().equals("1")) {
            return devUserService.login(loginUser.getUsername(), loginUser.getPassword()).getId();
        } else {
            return backendUserService.login(loginUser.getUsername(), loginUser.getPassword()).getId();
        }
    }

    @GetMapping("/logout")
    public AjaxResult logout(@RequestHeader("Token") String token) {
        SessionManager.getInstance().del(token);
        return AjaxResult.ok();
    }
}
